#include "StdAfx.h"
#include <stdlib.h>
#include "RandomInterleaver.h"

CRandomInterleaver::CRandomInterleaver(uint32_t size)
{
	mInterleaveIndex = new uint32_t[size];
	mDeInterleaveIndex = new uint32_t[size];
	mSize = size;
	if(mInterleaveIndex!=NULL)
	{
		//initialize
		for(uint32_t i=0;i<size;i++){
			mInterleaveIndex[i] = 0xFFFFFFFF;
		}
		//create random interleaving index
		for(uint32_t i=0;i<size;i++){
			uint32_t index =rand() % (size-1);
			if(mInterleaveIndex[index]==0xFFFFFFFF){
				//free slot
				mInterleaveIndex[index] = i;
				mDeInterleaveIndex[i] = index;
			}else{
				//flip a coin => 0 = left, 1= right
				uint32_t coin =rand() % 2;
				if(coin){
					//right
					while(mInterleaveIndex[index]!=0xFFFFFFFF){
						index = (index + 1) % size;
					}
				}else{ //left
					while(mInterleaveIndex[index]!=0xFFFFFFFF){
						if(index>0){
							index--;
						}else{
							index = size-1;
						}
					}
				}
				mInterleaveIndex[index] = i;
				mDeInterleaveIndex[i] = index;
				
			}
		}
	}  
	FILE* arq;
				arq = (fopen("int1.txt","w"));
				for(uint32_t i=0;i<size;i++){
					fprintf(arq,"%d ",mInterleaveIndex[i]);
				}
				fclose(arq);
};